package com.zhou.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class SqliteUtil {
	
	

	public static SQLiteDatabase openDatabase(Context context, String dbPath,
			String dbFileName) {

		try {
			String databaseFilename = dbPath + "/" + dbFileName;
			Log.i("db_filename", databaseFilename);
			File dir = new File(dbPath);
			Log.i("db_path", dbPath);
			// 如果/sdcard/dictionary目录中存在，创建这个目录
			if (!dir.exists())
				dir.mkdir();
			// 如果在/sdcard/dictionary目录中不存在
			// dictionary.db文件，则从res\raw目录中复制这个文件到
			// SD卡的目录（/sdcard/dictionary）
			if (!(new File(databaseFilename)).exists()) {
				// 获得封装dictionary.db文件的InputStream对象
				AssetManager assetManager = context.getResources().getAssets();
				// InputStream is = context.getResources().openRawResource(
				// rawFileName);
				InputStream is = assetManager.open(dbFileName);
				FileOutputStream fos = new FileOutputStream(databaseFilename);
				byte[] buffer = new byte[8192];
				int count = 0;
				// 开始复制dictionary.db文件
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
					System.out.println(count);
				}

				fos.close();
				is.close();
				
			}
			// 获得db文件的绝对路径
			
			Log.i("db_filename", databaseFilename);

			SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
					databaseFilename, null);
			Log.i("databaseHash", database.toString());
			return database;
		} catch (Exception e) {
		}
		return null;
	}

}
